package com.multicampus.sample.lucene.search.remote;

import java.rmi.Naming;
import java.util.Date;
import java.util.HashMap;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.MultiSearcher;
import org.apache.lucene.search.ParallelMultiSearcher;
import org.apache.lucene.search.Searchable;
import org.apache.lucene.search.TermQuery;

public class SearchClient {
	private static HashMap<String, MultiSearcher> searcherCache = new HashMap<String, MultiSearcher>();

	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			System.err.println("Usage: SearchClient <query>");
			System.exit(-1);
		}

		String word = args[0];

		for (int i = 0; i < 5; i++) {
			search(word);
		}
	}

	public static void search(String word) throws Exception {
		TermQuery query = new TermQuery(new Term("contents", word));

		ParallelMultiSearcher searcher = (ParallelMultiSearcher) searcherCache.get("search");

		if (searcher == null) {
			searcher = new ParallelMultiSearcher(
					new Searchable[] { lookupRemote("Searcher1"), lookupRemote("Searcher2") });
			searcherCache.put("search", searcher);
		}

		long begin = new Date().getTime();
		Hits hits = searcher.search(query);
		long end = new Date().getTime();

		System.out.println("Searched for '" + word + "' ("
				+ (end - begin) + " ms)");

		if (hits.length() == 0) {
			System.out.println("<NONE FOUND>");
		}

		for (int i = 0; i < hits.length(); i++) {
			Document doc = hits.doc(i);
			String value = doc.get("path");
			System.out.println(value);
		}

		System.out.println();
	}

	private static Searchable lookupRemote(String name) throws Exception {
		return (Searchable) Naming.lookup("//localhost/" + name);
	}

}
